package servlet;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;

import service.UserService;
import entity.User;


@WebServlet(urlPatterns={"/home"})
public class Home extends HttpServlet {
	
	UserService uservice=new UserService();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		HttpSession session=request.getSession();
		if(session.getAttribute("user")!=null){
			
			if(request.getParameter("action")!=null && request.getParameter("action").equalsIgnoreCase("logout")){
				session.invalidate();
				response.sendRedirect("");
			}
			else{			
				RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/home.jsp");
				if (dispatcher != null) dispatcher.forward(request, response);
			}
		}
		else{
			RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/login.jsp");
			if (dispatcher != null) dispatcher.forward(request, response);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		
		User user= uservice.loginUser(username, password);
		if(user!=null){
			HttpSession session=request.getSession();
			session.setAttribute("user", user);
			//response.sendRedirect("");
			response.sendRedirect("");
			
		}
	}

}
